package
{
	import com.happyelements.isolib.IsoWorld;
	import flash.geom.Point;
	import com.happyelements.display.constants.AnimationRendererStatus;
	import com.happyelements.display.HEMovieClip;
	import com.happyelements.isolib.IsoTileAnimation;
	import com.happyelements.data.DataModel;
	import com.happyelements.components.MapScene;

	/**
	 * @author dongpiggyi
	 */
	public class AddingTileState implements IMapSceneState
	{
		private var _context:MapSceneContext;
		
		private var _currentTileObject:IsoTileAnimation;

		private var _currentDataModel:DataModel;
		
		public function AddingTileState(context:MapSceneContext) 
		{
			_context = context;
		}
		
		public function onMouseDown(mapScene:MapScene, stageX:Number, stageY:Number):void
		{
//			trace("AddingTileState: " + "down");
			_context.currentX = stageX;
			_context.currentY = stageY;
		}

		public function onMouseMove(mapScene:MapScene, stageX:Number, stageY:Number):void
		{
//			trace("AddingTileState: " + "move");
			_context.beforeDraggingState = _context.addingTileState;
			_context.currentState = _context.draggingMapState;
		}

		public function onMouseUp(mapScene:MapScene, stageX:Number, stageY:Number):void
		{
//			trace("AddingTileState: " + "up");
			_context.beforeDraggingState = _context.draggingMapState;
			_context.currentState = _context.draggingMapState;
			
			_currentTileObject = null;
			_currentDataModel = null;
		}
		
		public function onAddingTile(mapScene:MapScene, stageX:Number, stageY:Number, currentDataModel:DataModel = null):void
		{
//			trace("AddingTileState: " + "adding");
			var point:Point = mapScene.convertPointToColRow(stageX, stageY);
			
			if(currentDataModel != _currentDataModel)
			{
				_currentTileObject ? IsoWorld.instance.removeTileObject(_currentTileObject) : null;
				_currentTileObject = createTileItem(currentDataModel.id, currentDataModel.source, currentDataModel.ref, 
					point.x, point.y, currentDataModel.rows, currentDataModel.cols);
					
//				trace("create tile object: " + _currentTileObject);
				
				_currentDataModel = currentDataModel;
			}
			
			if (IsoWorld.instance.canSetTileHere(_currentTileObject, point.x, point.y))
			{
//				trace("move to there");
				if(!mapScene.hasTileObject(_currentTileObject))
				{
//					trace("add tile object to isoworld");
					mapScene.addTileObject(_currentTileObject);
				}
				
				_currentTileObject.moveTo(point.x, point.y);
				mapScene.update();
			}
		}
		
		private function createTileItem(id:String, url:String, animationClass:String, row:int, col:int, rows:int, cols:int):IsoTileAnimation
		{
			var result:IsoTileAnimation = new IsoTileAnimation(row, col, rows, cols);
			var animationDisplayObject:HEMovieClip = new HEMovieClip(GlobalPara.ASSETS_BASE_PATH + url, animationClass, "");
			
			result.assetID = id;
			result.displayObject = animationDisplayObject;
			result.getTypedDisplayObject().animationStatus = AnimationRendererStatus.STOPED;
			
			return result;
		}
	}
}
